import router from './index'
import store from '../store';

let flag = false;
router.beforeEach((to, from, next) => {
    let tk = sessionStorage.getItem('tk');
    if (tk) {
        if (!store.state.nikeName) {
            let lastUrl = getLastUrl(window.location.href, '/#/');
            if (to.path == lastUrl && !flag && to.path != '/login') { //动态路由页面的刷新事件
                store.getters.getRealMenus.forEach(item => {
                    router.addRoute(item)
                })
                flag = true;
                router.replace(to.path) //replace,保证浏览器回退的时候能直接返回到上个页面，不会叠加
            }
        }
        next()
    } else if (to.path === '/login' || to.path === '/register') {
        next()
    } else {
        next('/login')
    }

})

var getLastUrl = (str, yourStr) => {
    return str.slice(str.lastIndexOf(yourStr) + 2)//取到浏览器出现网址的最后"
}